//
//  MyTrajectoryViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/31.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "ZZLayout.h"
#import "FSCalendar.h"
#import "TrajectoryDateHeader.h"
#import "TrajectoryItemCell.h"

#import "ProductDetailViewController.h"
#import "PortfilioDetailViewController.h"


#import "MyTrajectoryViewController.h"

@interface MyTrajectoryViewController ()
<UICollectionViewDelegate,
UICollectionViewDataSource,
ZZLayoutDelegate>{
}

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray <MyTrajectorySectionModel *>*dataArray;

@end

@implementation MyTrajectoryViewController

- (void)dealloc {
    
}

- (instancetype)initWith:(NSInteger)index {
    self = [super init];
    if (self) {
        switch (index) {
            case 0:{
                self.type = MyTrajectoryListType_package;
            } break;
            case 1:{
                self.type = MyTrajectoryListType_product;
            } break;
            case 2:{
                self.type = MyTrajectoryListType_case;
            } break;
            default:
                break;
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self refreshParam];
    [self request_footPrint];
}

- (void)refreshParam {
    self.pageSize = 10;
    self.pageNum = 1;
}

- (void)initView {
        
    self.view.backgroundColor = UIColorHex(0xf1f1f1);
    [self.view addSubview:self.collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
    }];
}

#pragma mark- 协议方法
//collectionView的协议方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArray[section].userBrowsingFootprintsList.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    // 区头
    if (kind == UICollectionElementKindSectionHeader) {
        TrajectoryDateHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TrajectoryDateHeader" forIndexPath:indexPath];
        
        headerView.sectionTitle.text = self.dataArray[indexPath.section].dateString;
        reusableView = headerView;
    }
    // 区尾
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" forIndexPath:indexPath];
        reusableView = footerView;
    }
    return reusableView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    /*
     //套餐
     MyTrajectoryListType_package    =2,
     //婚品
     MyTrajectoryListType_product    =4,
     //商家
     MyTrajectoryListType_case       =3,
     */
    switch (self.type) {
        case MyTrajectoryListType_package:{

            commonTrajectoryModel *model = self.dataArray[indexPath.section].userBrowsingFootprintsList[indexPath.row];
                        
            CommonPackageModel *packageModel = [[CommonPackageModel alloc] init];
            packageModel.goodsId = model.baseId;
            packageModel.goodsVersion = model.goodsVersion;
            packageModel.classId = model.classId;
            [[TT_JumpManager sharedManager] jumpWithDetailModel:packageModel completion:^(BOOL success, NSString * _Nonnull message) {}];

        } break;
        case MyTrajectoryListType_product:{

            ProductDetailViewController *vc = [[ProductDetailViewController alloc] init];
            vc.goodsId = self.dataArray[indexPath.section].userBrowsingFootprintsList[indexPath.row].baseId;
            [self.navigationController pushViewController:vc animated:YES];
        } break;
        case MyTrajectoryListType_case:{

            PortfilioDetailViewController *vc = [[PortfilioDetailViewController alloc] init];
            vc.soId = self.dataArray[indexPath.section].userBrowsingFootprintsList[indexPath.row].baseId;
            [self.navigationController pushViewController:vc animated:YES];
            
        } break;
        default:
            break;
    }

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    TrajectoryItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TrajectoryItemCellID" forIndexPath:indexPath];
    [cell fillCellWithModel:self.dataArray[indexPath.section].userBrowsingFootprintsList[indexPath.row] Type:self.type];
    return cell;
}

//ZZLyout的流协议方法
- (CGFloat)layout:(ZZLayout *)layout heightForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的高

    return self.dataArray[indexPath.section].userBrowsingFootprintsList[indexPath.row].itemHeight;
}

- (NSInteger)layout:(ZZLayout *)layout columnNumberAtSection:(NSInteger)section {//每个区有几列

    return 3;
}

- (UIEdgeInsets)layout:(ZZLayout *)layout insetForSectionAtIndex:(NSInteger)section {//设置每个区的边距
    
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

- (NSInteger)layout:(ZZLayout *)layout lineSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的行间距

    return 10;
}

- (CGFloat)layout:(ZZLayout*)layout interitemSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的列间距

    return 10;
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section {//设置区头的高度

    return CGSizeMake(TTScreenWidth, 40);
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForFooterInSection:(NSInteger)section {//设置区尾的高度
    return CGSizeMake(TTScreenWidth, CGFLOAT_MIN);
}

- (CGFloat)layout:(ZZLayout*)layout spacingWithLastSectionForSectionAtIndex:(NSInteger)section {//本区区头和上个区区尾的间距
    return 0;
}

- (UIColor *)layout:(UICollectionView *)layout colorForSection:(NSInteger)section {//设置不同分区的不同背景颜色
    return UIColorHex(0xf1f1f1);
}

#pragma mark- 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        ZZLayout *layout = [[ZZLayout alloc] initWith:ZZLayoutFlowTypeVertical delegate:self];
        //打开区头悬浮功能(默认关闭)
        layout.sectionHeadersPinToVisibleBounds = NO;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = UIColorHex(0xf1f1f1);
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"TrajectoryItemCell" bundle:nil] forCellWithReuseIdentifier:@"TrajectoryItemCellID"];

        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader"];
//
        [_collectionView registerNib:[UINib nibWithNibName:@"TrajectoryDateHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TrajectoryDateHeader"];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"];

        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;

        _collectionView.bounces = YES;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
    }
    return _collectionView;
}

- (NSMutableArray<MyTrajectorySectionModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (void)request_footPrint {

    NSMutableDictionary *dic = @{}.mutableCopy;
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_FootPrintList];
    
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];

    NSMutableDictionary *t = @{}.mutableCopy;
    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [t setValue:@(self.type) forKey:@"footType"];
    [t setValue:@([Utilities getCurrentTimestamp]) forKey:@"updateTime"];
    
    [dic setValue:t forKey:@"t"];
    
    [SVProgressHUD showWithStatus:@"正在加载"];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSArray *resultArray = [data valueForKey:@"data"];
                        
                if ([resultArray isKindOfClass:[NSArray class]]) {
                    
                    for (int i = 0; i < resultArray.count; i++) {
                        NSDictionary *resultArrayDic = resultArray[i];
                        if ([resultArrayDic isKindOfClass:[NSDictionary class]]) {
                            MyTrajectorySectionModel *model = [MyTrajectorySectionModel modelWithDictionary:resultArrayDic];

                            NSArray *userBrowsingFootprintsList = [resultArrayDic valueForKey:@"userBrowsingFootprintsList"];
                            if ([userBrowsingFootprintsList isKindOfClass:[NSArray class]]) {
                                model.userBrowsingFootprintsList = @[].mutableCopy;
                                for (int j = 0; j < userBrowsingFootprintsList.count; j++) {
                                    NSDictionary *footDic = userBrowsingFootprintsList[j];
                                    commonTrajectoryModel *footmodel = [commonTrajectoryModel modelWithDictionary:footDic];
                                    NSString *url = [TT_OSSManager reSourceUrl:footmodel.url type:BA_resizeType_plus];
                                    footmodel.url = url;
                                    footmodel.itemHeight = [TrajectoryItemCell calculateHeightWithWidth:TTScreenWidth];
                                    
                                    footmodel.footType = weakSelf.type;
                                    [model.userBrowsingFootprintsList addObject:footmodel];
                                }
                            }
                            
                            [weakSelf.dataArray addObject:model];
                        }
                    }
                    [weakSelf.collectionView reloadData];
                }
            }
        }

        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
    
}

@end
